﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Dynamic;
using System.Collections;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Security;
using System.Data;
using System.Data.OleDb;
using System.Xml.Linq;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
/// <summary>
///WeiXin 的摘要说明
/// </summary>
namespace Common
{
    public class WeiXin
    {
        public WeiXin()
        {

        }
        #region
        public static string Token = "weixinjiafen";

        public static void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        public dynamic ConvertJson(string json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
            dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic;
            return dy;
        }

        public string HttpPost(string Url, string postDataStr)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            byte[] data = encoding.GetBytes(postDataStr);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(Url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        public class DynamicJsonConverter : JavaScriptConverter
        {
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                if (dictionary == null)
                    throw new ArgumentNullException("dictionary");

                if (type == typeof(object))
                {
                    return new DynamicJsonObject(dictionary);
                }

                return null;
            }

            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {
                throw new NotImplementedException();
            }

            public override IEnumerable<Type> SupportedTypes
            {
                get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
            }
        }
        public class DynamicJsonObject : DynamicObject
        {
            private IDictionary<string, object> Dictionary { get; set; }

            public DynamicJsonObject(IDictionary<string, object> dictionary)
            {
                this.Dictionary = dictionary;
            }

            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                result = this.Dictionary[binder.Name];

                if (result is IDictionary<string, object>)
                {
                    result = new DynamicJsonObject(result as IDictionary<string, object>);
                }
                else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
                {
                    result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
                }
                else if (result is ArrayList)
                {
                    result = new List<object>((result as ArrayList).ToArray());
                }

                return this.Dictionary.ContainsKey(binder.Name);
            }
        }
        public string PostInput(System.Web.HttpRequest request)
        {
            try
            {
                return PostInput(request, Encoding.UTF8);
            }
            catch (Exception ex)
            { throw ex; }
        }

        /// <summary>
        /// 获取POST返回来的数据
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <param name="encoding">编码格式</param>
        /// <returns></returns>
        public string PostInput(System.Web.HttpRequest request, Encoding encoding)
        {
            StringBuilder builder = new StringBuilder();
            try
            {
                using (System.IO.Stream s = request.InputStream)
                {
                    int count = 0;
                    byte[] buffer = new byte[1024];
                    while ((count = s.Read(buffer, 0, 1024)) > 0)
                    {
                        builder.Append(encoding.GetString(buffer, 0, count));
                    }
                    s.Flush();
                    s.Close();
                    s.Dispose();
                }
                return builder.ToString();
            }
            catch (Exception ex)
            { throw ex; }
        }

        public string XmlToJson(string xml)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xml);
            System.Xml.XmlNodeList nodelist = doc.ChildNodes[0].ChildNodes;
            string json = "{";
            foreach (System.Xml.XmlNode node in nodelist)
            {
                string n = node.Name;
                json += node.Name + ":'" + node.InnerText + "',";
            }
            json = json.TrimEnd(',');
            json += "}";
            return json;
        }

        public class DynamicHelper
        {
            public static string ToXml(dynamic dynamicObject)
            {
                DynamicXElement xmlNode = dynamicObject;
                return xmlNode.XContent.ToString();
            }

            public static dynamic ToObject(string xml, dynamic dynamicResult)
            {
                XElement element = XElement.Parse(xml);
                dynamicResult = new DynamicXElement(element);
                return dynamicResult;
            }

            public static dynamic ToObject(string xml)
            {
                XElement element = XElement.Parse(xml);
                dynamic dynamicResult = new DynamicXElement(element);
                return dynamicResult;
            }
        }
        public static dynamic XmlStringToDynamic(string xml)
        {
            if (String.IsNullOrEmpty(xml))
                return null;
            XElement element = XElement.Parse(xml);
            dynamic dynamicResult = new DynamicXMLNode(element);
            return dynamicResult;
        }
        public class DynamicXMLNode : DynamicObject
        {
            public DynamicXMLNode() { }

            XElement node;

            public XElement Element
            {
                get
                {
                    return node;
                }
            }

            public DynamicXMLNode(XElement node)
            {
                this.node = node;
            }

            public DynamicXMLNode(string name)
            {
                node = new XElement(name);
            }

            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                if (binder.Name == "Value")
                {
                    result = node.Value;
                    return true;
                }
                if (binder.Name == "ElementCount")
                {
                    if (node.HasElements)
                        result = node.Elements().Count();
                    else
                        result = 0;
                    return true;
                }
                XElement getNode;
                try
                {
                    getNode = node.Element(binder.Name);
                }
                catch
                {
                    result = null;
                    return true;
                }
                if (getNode != null)
                {
                    result = new DynamicXMLNode(getNode);
                    return true;
                }
                else
                {
                    result = null;
                    return false;
                }
            }


        }
        public class DynamicXElement : DynamicObject
        {
            public DynamicXElement(XElement node)
            {
                this.XContent = node;
            }

            public DynamicXElement()
            {
            }

            public DynamicXElement(String name)
            {
                this.XContent = new XElement(name);
            }

            public XElement XContent
            {
                get;
                private set;
            }

            public override bool TrySetMember(
                SetMemberBinder binder, object value)
            {
                XElement setNode = this.XContent.Element(binder.Name);
                if (setNode != null)
                    setNode.SetValue(value);
                else
                {
                    //creates an XElement without a value.
                    if (value.GetType() == typeof(DynamicXElement))
                        this.XContent.Add(new XElement(binder.Name));
                    else
                        this.XContent.Add(new XElement(binder.Name, value));
                }
                return true;
            }

            public override bool TryGetMember(
                GetMemberBinder binder, out object result)
            {
                XElement getNode = this.XContent.Element(binder.Name);
                if (getNode != null)
                {
                    result = new DynamicXElement(getNode);
                }
                else
                {
                    result = new DynamicXElement(binder.Name);
                }
                return true;
            }

            public override bool TryConvert(ConvertBinder binder, out object result)
            {
                if (binder.Type == typeof(String))
                {
                    result = this.XContent.Value;
                    return true;
                }
                else
                {
                    result = null;
                    return false;
                }
            }
        }

        public void SaveFile(string downurl, string saveurl)
        {
            int blocksize = 1024 * 100;
            byte[] buffer = new byte[blocksize];

            string strFileName = HttpContext.Current.Server.MapPath(saveurl);

            WebRequest request = WebRequest.Create(downurl);
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();

            FileStream writer = new FileStream(strFileName, FileMode.OpenOrCreate, FileAccess.Write);
            int c = 0;
            while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                writer.Write(buffer, 0, c);
            }
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            response.Close();
        }
        //using System.Drawing;
        //using System.IO;
        //using System.Drawing.Imaging;

        public void AddTextToImg(string fileName, string text, int x, int y)
        {
            if (!File.Exists(HttpContext.Current.Server.MapPath(fileName)))
            {
                throw new FileNotFoundException("The file don't exist!");
            }

            if (text == string.Empty)
            {
                return;
            }
            //还需要判断文件类型是否为图像类型，这里就不赘述了

            System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(fileName));
            Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
            Graphics g = Graphics.FromImage(bitmap);

            float fontSize = 16.0f;    //字体大小
            float textWidth = text.Length * fontSize;  //文本的长度
            //下面定义一个矩形区域，以后在这个矩形里画上白底黑字
            float rectX = x;
            float rectY = y;
            float rectWidth = text.Length * (fontSize + 8) * 2;
            float rectHeight = fontSize + 10;
            //声明矩形域
            RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);

            Font font = new Font("微软雅黑", fontSize, FontStyle.Bold);   //定义字体
            Brush whiteBrush = new SolidBrush(Color.White);   //白笔刷，画文字用
            //Brush blackBrush = new SolidBrush(Color.FromArgb(147,188,32));   //黑笔刷，画背景用
            Brush blackBrush = new SolidBrush(Color.Transparent);
            g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);

            g.DrawString(text, font, whiteBrush, textArea);
            MemoryStream ms = new MemoryStream();

            //设置文字水印质量
            EncoderParameter p;
            EncoderParameters ps;
            ps = new EncoderParameters(1);
            p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
            ps.Param[0] = p;

            //保存为Jpg类型
            ImageCodecInfo ii = GetCodecInfo("image/jpeg");
            bitmap.Save(ms, ii, ps);
            byte[] imgData = ms.ToArray();
            //输出处理后的图像，这里为了演示方便，我将图片显示在页面中了
            //Response.Clear();
            //Response.ContentType = "image/jpeg";
            //Response.BinaryWrite(ms.ToArray());

            g.Dispose();
            bitmap.Dispose();
            image.Dispose();

            FileStream fs = null;
            File.Delete(HttpContext.Current.Server.MapPath(fileName));
            fs = new FileStream(HttpContext.Current.Server.MapPath(fileName), FileMode.Create, FileAccess.Write);
            if (fs != null)
            {
                fs.Write(imgData, 0, imgData.Length);
                fs.Close();
            }
        }
        /// <summary>   
        /// 给图片上水印   
        /// </summary>   
        /// <param name="filePath">原图片地址</param>   
        /// <param name="waterFile">水印图片地址</param>   
        public void MarkWater(string filePath, string waterFile, int left, int top)
        {
            //GIF不水印   
            int i = filePath.LastIndexOf(".");
            string ex = filePath.Substring(i, filePath.Length - i);
            if (string.Compare(ex, ".gif", true) == 0)
            {
                return;
            }

            string ModifyImagePath = HttpContext.Current.Server.MapPath(filePath);//修改的图像路径   
            int lucencyPercent = 100;
            System.Drawing.Image modifyImage = null;
            System.Drawing.Image drawedImage = null;
            Graphics g = null;
            try
            {
                //建立图形对象   
                modifyImage = System.Drawing.Image.FromFile(ModifyImagePath, true);
                drawedImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(waterFile), true);
                g = Graphics.FromImage(modifyImage);
                //获取要绘制图形坐标   
                int x = left;// modifyImage.Width - drawedImage.Width;
                int y = top;// modifyImage.Height - drawedImage.Height;
                //设置颜色矩阵   
                float[][] matrixItems ={   
            new float[] {1, 0, 0, 0, 0},   
            new float[] {0, 1, 0, 0, 0},   
            new float[] {0, 0, 1, 0, 0},   
            new float[] {0, 0, 0, (float)lucencyPercent/100f, 0},   
            new float[] {0, 0, 0, 0, 1}};

                ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
                ImageAttributes imgAttr = new ImageAttributes();
                imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                //绘制阴影图像   
                g.DrawImage(drawedImage, new Rectangle(x, y, drawedImage.Width, drawedImage.Height), 0, 0, drawedImage.Width, drawedImage.Height, GraphicsUnit.Pixel, imgAttr);
                //保存文件   
                string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
                FileInfo fi = new FileInfo(ModifyImagePath);
                ImageFormat imageType = ImageFormat.Gif;
                switch (fi.Extension.ToLower())
                {
                    case ".jpg": imageType = ImageFormat.Jpeg; break;
                    case ".gif": imageType = ImageFormat.Gif; break;
                    case ".png": imageType = ImageFormat.Png; break;
                    case ".bmp": imageType = ImageFormat.Bmp; break;
                    case ".tif": imageType = ImageFormat.Tiff; break;
                    case ".wmf": imageType = ImageFormat.Wmf; break;
                    case ".ico": imageType = ImageFormat.Icon; break;
                    default: break;
                }
                MemoryStream ms = new MemoryStream();
                //设置图片水印质量
                EncoderParameter p;
                EncoderParameters ps;
                ps = new EncoderParameters(1);
                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                ps.Param[0] = p;

                ImageCodecInfo ii = GetCodecInfo("image/jpeg");
                modifyImage.Save(ms, ii, ps);
                byte[] imgData = ms.ToArray();
                modifyImage.Dispose();
                drawedImage.Dispose();
                g.Dispose();
                FileStream fs = null;
                File.Delete(ModifyImagePath);
                fs = new FileStream(ModifyImagePath, FileMode.Create, FileAccess.Write);
                if (fs != null)
                {
                    fs.Write(imgData, 0, imgData.Length);
                    fs.Close();
                }
            }
            finally
            {
                try
                {
                    drawedImage.Dispose();
                    modifyImage.Dispose();
                    g.Dispose();
                }
                catch
                {
                }
            }
        }
        public ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        /// 生成缩略图 
        /// </summary> 
        /// <param name="originalImagePath">源图路径（物理路径）</param> 
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param> 
        /// <param name="width">缩略图宽度</param> 
        /// <param name="height">缩略图高度</param> 
        /// <param name="mode">生成缩略图的方式</param>     
        public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(originalImagePath));

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                 
                    break;
                case "W"://指定宽，高按比例                     
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板 
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(HttpContext.Current.Server.MapPath(thumbnailPath), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 制作缩略图
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
        {
            //2012-02-05修改过，支持替换
            byte[] imageBytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath(fileName));
            System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(imageBytes));
            MakeThumbnailImage(img, newFileName, maxWidth, maxHeight);
            //原文
            //MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight);
        }
        /// <summary>
        /// 制作缩略图
        /// </summary>
        /// <param name="original">图片对象</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeThumbnailImage(System.Drawing.Image original, string newFileName, int maxWidth, int maxHeight)
        {
            Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);

            using (System.Drawing.Image displayImage = new Bitmap(original, _newSize))
            {
                try
                {
                    displayImage.Save(HttpContext.Current.Server.MapPath(newFileName), original.RawFormat);
                    original.Dispose();

                }
                finally
                {
                    original.Dispose();
                }
            }
        }

        /// <summary>
        /// 计算新尺寸
        /// </summary>
        /// <param name="width">原始宽度</param>
        /// <param name="height">原始高度</param>
        /// <param name="maxWidth">最大新宽度</param>
        /// <param name="maxHeight">最大新高度</param>
        /// <returns></returns>
        private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
        {
            //此次2012-02-05修改过=================
            if (maxWidth <= 0)
                maxWidth = width;
            if (maxHeight <= 0)
                maxHeight = height;
            //以上2012-02-05修改过=================
            decimal MAX_WIDTH = (decimal)maxWidth;
            decimal MAX_HEIGHT = (decimal)maxHeight;
            decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;

            int newWidth, newHeight;
            decimal originalWidth = (decimal)width;
            decimal originalHeight = (decimal)height;

            if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
            {
                decimal factor;
                // determine the largest factor 
                if (originalWidth / originalHeight > ASPECT_RATIO)
                {
                    factor = originalWidth / MAX_WIDTH;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
                else
                {
                    factor = originalHeight / MAX_HEIGHT;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
            }
            else
            {
                newWidth = width;
                newHeight = height;
            }
            return new Size(newWidth, newHeight);
        }

        /*数据库操作*/
        static string conStr = "provider=microsoft.jet.oledb.4.0;data source=D:/exiaoke/crm/weixin/weixin.mdb";
        //static string conStr = "provider=microsoft.jet.oledb.4.0;data source=F:/webtest/weixin/weixin.mdb";
        public static PagedDataSource Pager(string tablename, string filter, int pagesize, int pageindex, ref int rowscount)
        {

            OleDbConnection objConn = new OleDbConnection(conStr);
            string sql = "select * from " + tablename + " where 1=1 " + filter;
            OleDbDataAdapter objCommand = new OleDbDataAdapter(sql, objConn);
            DataSet ds = new DataSet();
            objCommand.Fill(ds);
            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = ds.Tables[0].DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = pagesize; //每页文章显示的条数
            rowscount = objPds.DataSourceCount;
            objPds.CurrentPageIndex = pageindex - 1;
            return objPds;
        }
        /**/
        /// <summary>
        /// 获取当前页应该显示的记录，注意：查询中必须包含名为ID的自动编号列，若不符合你的要求，就修改一下源码吧 :)
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">分页容量</param>
        /// <param name="showString">显示的字段</param>
        /// <param name="queryString">查询字符串，支持联合查询</param>
        /// <param name="whereString">查询条件，若有条件限制则必须以where 开头</param>
        /// <param name="orderString">排序规则</param>
        /// <param name="pageCount">传出参数：总页数统计</param>
        /// <param name="recordCount">传出参数：总记录统计</param>
        /// <returns>装载记录的DataTable</returns>
        public static DataTable ExecutePager(int pageIndex, int pageSize, string showString, string queryString, string whereString, string orderString, out int pageCount, out int recordCount)
        {
            OleDbConnection objConn = new OleDbConnection(conStr);
            if (pageIndex < 1) pageIndex = 1;
            if (pageSize < 1) pageSize = 10;
            if (string.IsNullOrEmpty(showString)) showString = "*";
            if (string.IsNullOrEmpty(orderString)) orderString = "ID desc";
            objConn.Open();
            string myVw = string.Format(" ( {0} ) tempVw ", queryString);
            OleDbCommand cmdCount = new OleDbCommand(string.Format(" select count(0) as recordCount from {0} {1}", myVw, whereString), objConn);
            recordCount = Convert.ToInt32(cmdCount.ExecuteScalar());
            if ((recordCount % pageSize) > 0)
                pageCount = recordCount / pageSize + 1;
            else
                pageCount = recordCount / pageSize;
            OleDbCommand cmdRecord;
            if (pageIndex == 1)//第一页
            {
                cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, whereString, orderString), objConn);
            }
            else if (pageIndex > pageCount)//超出总页数
            {
                cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, "where 1=2", orderString), objConn);
            }
            else
            {
                int pageLowerBound = pageSize * pageIndex;
                int pageUpperBound = pageLowerBound - pageSize;
                string recordIDs = recordID(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageLowerBound, "ID", myVw, whereString, orderString), pageUpperBound);
                cmdRecord = new OleDbCommand(string.Format("select {0} from {1} where id in ({2}) order by {3} ", showString, myVw, recordIDs, orderString), objConn);
            }
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdRecord);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            objConn.Close();
            objConn.Dispose();
            return dt;
        }
        private static string recordID(string query, int passCount)
        {
            OleDbConnection objConn = new OleDbConnection(conStr);
            OleDbCommand cmd = new OleDbCommand(query, objConn);
            string result = string.Empty;
            using (IDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    if (passCount < 1)
                    {
                        result += "," + dr.GetInt32(0);
                    }
                    passCount--;
                }
            }
            return result.Substring(1);
        }
        public static int ExecuteNonQuery(string text)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = text;
            odc.Connection = con;
            con.Open();
            int count = odc.ExecuteNonQuery();
            con.Close();
            con.Dispose();
            return count;
        }
        public static OleDbDataReader ExecuteReader(OleDbConnection con, string text)
        {
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = text;
            odc.Connection = con;
            con.Open();
            OleDbDataReader dr = odc.ExecuteReader();
            return dr;
        }
        public static DataRow ExecuteRow(string text)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = text;
            odc.Connection = con;
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(odc);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            return dt.Rows[0];
        }
        public static object ExecuteScalar(string text)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = text;
            odc.Connection = con;
            con.Open();
            object single = odc.ExecuteScalar();
            con.Close();
            con.Dispose();
            return single;
        }
        public static string getColumnById(int id, string columnout, string table)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = "select " + columnout + " from " + table + " where id=" + id;
            odc.Connection = con;
            con.Open();
            string single = odc.ExecuteScalar() + "";
            con.Close();
            con.Dispose();
            return single;
        }
        public static string getColumnByOpenId(string openid, string columnout, string table)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = "select " + columnout + " from " + table + " where openid='" + openid + "'";
            odc.Connection = con;
            con.Open();
            string single = odc.ExecuteScalar() + "";
            con.Close();
            con.Dispose();
            return single;
        }
        public static int DeleteById(int id, string table)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = "delete from " + table + " where id=" + id;
            odc.Connection = con;
            con.Open();
            int single = odc.ExecuteNonQuery();
            con.Close();
            con.Dispose();
            return single;
        }
        public static int DeleteByOpenId(string openid, string table)
        {
            OleDbConnection con = new OleDbConnection(conStr);
            OleDbCommand odc = new OleDbCommand();
            odc.CommandText = "delete from " + table + " where openid='" + openid + "'";
            odc.Connection = con;
            con.Open();
            int single = odc.ExecuteNonQuery();
            con.Close();
            con.Dispose();
            return single;
        }
        public static string CutString(string stringToSub, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    nLength += 2;
                }
                else
                {
                    nLength = nLength + 1;
                }

                if (nLength <= (length * 2))
                {
                    sb.Append(stringChar[i]);
                }
                else
                {
                    break;
                }
            }
            if (sb.ToString() != stringToSub)
            {
                sb.Append("...");
            }
            return sb.ToString();
        }
        //添加关注者
        public static bool AddUsers(int pid, string openid, string name, string sex, string head, string province, string city)
        {
            string sql = "insert into users(pid,openid,name,sex,head,province,city,createdate) values(" + pid + ",'" + openid + "','" + name + "','" + sex + "','" + head + "','" + province + "','" + city + "','" + DateTime.Now + "')";
            int flag = ExecuteNonQuery(sql);
            if (flag == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        //修改关注者
        public static bool UpdateUsers(string openid, string name, string sex, string province, string city, string ewm)
        {
            string sql = "update users set name='" + name + "',sex='" + sex + "',province='" + province + "',city='" + city + "',ewm='" + ewm + "' where openid='" + openid + "'";
            int flag = ExecuteNonQuery(sql);
            if (flag == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
    }
}